<?php

namespace Beike\Admin\Services;

use Illuminate\Support\Facades\DB;

class MenuImport
{
    /**
     * Import menu settings from a CSV file
     *
     * @param string $filePath Path to the CSV file
     * @return array Result of the import process
     */
    public static function importMenu(string $filePath): array
    {
        try {
            // Check if file exists and is readable
            if (!file_exists($filePath) || !is_readable($filePath)) {
                return [
                    'success' => 0,
                    'errors' => ["File not found or not readable: $filePath"],
                    'skipped' => 0,
                ];
            }

            // Initialize results and menu structure
            $result = ['success' => 0, 'errors' => [], 'skipped' => 0];
            $menuStructure = [];
            $categoryMap = []; // Map category names to IDs

            // Read CSV file
            $file = fopen($filePath, 'r');
            $header = fgetcsv($file); // Read header row

            // Begin database transaction
            DB::beginTransaction();

            // Collect categories by level
            $categories = ['level1' => [], 'level2' => [], 'level3' => []];
            $lineNumber = 2; // Start from line 2 (after header)
            while (($row = fgetcsv($file)) !== false) {
                try {
                    $topCategory = trim($row[0]);
                    $parentCategory = trim($row[1]);
                    $category = trim($row[2]);
                    $level = (int) $row[3];

                    // Validate input
                    if (empty($category) || !in_array($level, [1, 2, 3])) {
                        $result['skipped']++;
                        $result['errors'][] = "Invalid data at line $lineNumber: Empty category or invalid level";
                        $lineNumber++;
                        continue;
                    }

                    // Store categories by level
                    if ($level === 1) {
                        $categories['level1'][$category] = [
                            'top_category' => $topCategory,
                            'category' => $category,
                        ];
                    } elseif ($level === 2) {
                        $categories['level2'][$category] = [
                            'top_category' => $topCategory,
                            'parent_category' => $parentCategory,
                            'category' => $category,
                        ];
                    } elseif ($level === 3) {
                        $categories['level3'][$category] = [
                            'top_category' => $topCategory,
                            'parent_category' => $parentCategory,
                            'category' => $category,
                        ];
                    }

                    $result['success']++;
                } catch (\Exception $e) {
                    $result['errors'][] = "Error processing '$category' at line $lineNumber: " . $e->getMessage();
                    $lineNumber++;
                    continue;
                }
                $lineNumber++;
            }
            fclose($file);

            // Build menu structure
            foreach ($categories['level1'] as $level1Name => $level1Data) {
                $menuItem = [
                    'isFull' => false,
                    'badge' => [
                        'isShow' => false,
                        'name' => ['en' => '', 'zh_cn' => ''],
                        'bg_color' => '#fd560f',
                        'text_color' => '#ffffff',
                    ],
                    'link' => [
                        'type' => 'category',
                        'value' => self::getCategoryId($level1Name),
                        'text' => [],
                        'link' => '',
                    ],
                    'name' => [
                        'en' => $level1Name,
                        'zh_cn' => '',
                    ],
                    'isChildren' => false,
                    'childrenGroup' => [],
                ];

                // Add level 2 categories under this level 1
                foreach ($categories['level2'] as $level2Name => $level2Data) {
                    if ($level2Data['top_category'] === $level1Name || $level2Data['parent_category'] === $level1Name) {
                        $childrenGroup = [
                            'name' => [
                                'en' => $level2Name,
                                'zh_cn' => '',
                            ],
                            'type' => '',
                            'image' => [
                                'image' => [],
                                'link' => ['type' => 'product', 'value' => '', 'text' => []],
                            ],
                            'children' => [],
                        ];

                        // Add level 3 categories under this level 2
                        foreach ($categories['level3'] as $level3Name => $level3Data) {
                            if ($level3Data['parent_category'] === $level2Name && $level3Data['top_category'] === $level1Name) {
                                $childrenGroup['children'][] = [
                                    'name' => [],
                                    'link' => [
                                        'type' => 'category',
                                        'value' => self::getCategoryId($level3Name),
                                        'text' => ['en' => '', 'zh_cn' => ''],
                                        'link' => '',
                                    ],
                                ];
                            }
                        }

                        $menuItem['childrenGroup'][] = $childrenGroup;
                    }
                }

                $menuStructure[] = $menuItem;
            }

            // Wrap menu structure in "menus" key
            $finalMenuStructure = ['menus' => $menuStructure];

            // Insert or update menu settings in the settings table
            $updated = DB::table('settings')
                ->where([
                    'type' => 'system',
                    'space' => 'base',
                    'name' => 'menu_setting',
                ])
                ->update([
                    'value' => json_encode($finalMenuStructure),
                    'json' => 1,
                    'updated_at' => now(),
                ]);

            if ($updated === 0) {
                DB::rollBack();
                return [
                    'success' => 0,
                    'errors' => ["No menu_setting record found to update or no changes applied"],
                    'skipped' => 0,
                ];
            }

            // Commit transaction
            DB::commit();
            return $result;

        } catch (\Exception $e) {
            // Rollback on error
            DB::rollBack();
            return [
                'success' => 0,
                'errors' => ["Failed to process CSV: " . $e->getMessage()],
                'skipped' => 0,
            ];
        }
    }

    /**
     * Map category names to IDs by querying category_descriptions
     *
     * @param string $categoryName Category name
     * @return int|string Category ID or empty string
     */
    private static function getCategoryId(string $categoryName)
    {
        $category = DB::table('category_descriptions')
            ->where('name', $categoryName)
            ->where('locale', 'en')
            ->first();
        return $category ? $category->category_id : '';
    }
}
?>